const { PDFDocument } = require('pdf-lib')
const crypto = require('crypto');
const path = require('node:path')
const fs = require('node:fs')

module.exports.mergePages = async function (arg) {
    const resPdfDoc = await PDFDocument.create()
    const testDocHash = {}
    let skipped = 0

    for (let i = 0; i < arg.files.length; i++) {
        const file1 = fs.readFileSync(arg.files[i])
        const fPdfDoc = await PDFDocument.load(file1)
        const n = fPdfDoc.getPageCount();
        for (let k = 0; k < n; k++) {
            if (arg.repeat) {
                const testMd5Doc = await PDFDocument.create()
                const [page1] = await testMd5Doc.copyPages(fPdfDoc, [k])

                testMd5Doc.addPage(page1)
                const doc_base64 = await testMd5Doc.saveAsBase64()
                const md5 = crypto.createHash('md5');
                const result = md5.update(doc_base64).digest('hex');
                console.log(result)
                if (!testDocHash[result]) {
                    testDocHash[result] = true;
                    const [real_page] = await resPdfDoc.copyPages(fPdfDoc, [k])
                    resPdfDoc.addPage(real_page)
                } else {
                    console.log('页面存在，跳过！', result)
                    skipped = skipped + 1
                }
            } else {
                const [real_page] = await resPdfDoc.copyPages(fPdfDoc, [k])
                resPdfDoc.addPage(real_page)
            }
        }
    }

    resPdfDoc.setAuthor('by cadcamzy@hotmail.com')
    resPdfDoc.setCreationDate(new Date())
    resPdfDoc.setCreator('pdf_node')

    const pdfBytes = await resPdfDoc.save()

    try {
        fs.accessSync(arg.sfont)
        return -1
    } catch (error) {
        fs.writeFileSync(arg.sfont, pdfBytes)
        return skipped
    }
}

module.exports.getPageCount = async function (arg) {
    let n = 0;
    try {
        const file1 = fs.readFileSync(arg)
        const fPdfDoc = await PDFDocument.load(file1)
        n = fPdfDoc.getPageCount();
    } catch (error) {
        n = -1
    }

    return n
}

async function savePdfFile(resPdfDoc, filePath){
    resPdfDoc.setAuthor('by cadcamzy@hotmail.com')
    resPdfDoc.setCreationDate(new Date())
    resPdfDoc.setCreator('pdf_node')

    const pdfBytes = await resPdfDoc.save()

    try {
        fs.accessSync(filePath)
        return -1
    } catch (error) {
        fs.writeFileSync(filePath, pdfBytes)
        return 1
    }
}

module.exports.splitPages = async function (arg) {
    let result_arr = []

    const file1 = fs.readFileSync(arg.file)
    const fileName = path.basename(arg.file)
    const fPdfDoc = await PDFDocument.load(file1)

    for (let i = 0; i < arg.range.length; i++) {
        const resPdfDoc = await PDFDocument.create()
        let [s, e] = arg.range[i].split('~')
        s = s ? s * 1 - 1 : -1;
        e = e ? e * 1 - 1 : -1;
        if( s >= 0 && e >= 0) {
            for(let k = s; k <= e; k ++){
                const [real_page] = await resPdfDoc.copyPages(fPdfDoc, [k])
                resPdfDoc.addPage(real_page)
            }
            const result_s = await savePdfFile(resPdfDoc, path.join(arg.sdir, fileName.replace('.pdf', `~${i+1}.pdf`)))
            result_arr.push({[arg.range[i]]: result_s})
        }else if( s >= 0 ) {
            const [real_page] = await resPdfDoc.copyPages(fPdfDoc, [s])
            resPdfDoc.addPage(real_page)

            const result_s = await savePdfFile(resPdfDoc, path.join(arg.sdir, fileName.replace('.pdf', `~${i+1}.pdf`)))
            result_arr.push({[arg.range[i]]: result_s})
        }
    }
    return result_arr;
}